package com.zfcoding.redis.service.impl;


import com.zfcoding.redis.entity.User;
import com.zfcoding.redis.service.UserService;
import com.zfcoding.redis.util.JSONUtil;
import io.reactivex.Single;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;


@Service("UserService")
public class UserServiceImp implements UserService {
    //解决Redis乱码问题 --
    private static final StringRedisSerializer STRING_SERIALIZER = new StringRedisSerializer();
    private static final GenericJackson2JsonRedisSerializer JACKSON__SERIALIZER = new GenericJackson2JsonRedisSerializer();


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

//    @Autowired
    //坑 - 1.自动注入要使用
    //https://www.cnblogs.com/toutou/p/could_not_be_found.html
    @Resource
    private RedisTemplate<String,Serializable> redisTemplate;

    private static String REDIS_KEY = "user:%s";



    @Override
    public List<User> getUsers() {
        return null;
    }

    @Override
    public User getUser(Integer id) {
        var key = String.format(REDIS_KEY,id);
        return (User) redisTemplate.opsForValue().get(key);
    }

    @Override
    public Boolean saveUser(User user) {
        redisTemplate.setKeySerializer(STRING_SERIALIZER);
        redisTemplate.setValueSerializer(JACKSON__SERIALIZER);
        var key = String.format(REDIS_KEY,user.getId());
        //表示的是否set
        //如果Value设置是一个String类型(JSONUtil.toJSONString(user)),获取的时候会报错...
        //return redisTemplate.opsForValue().setIfAbsent(key, JSONUtil.toJSONString( user));
        return redisTemplate.opsForValue().setIfAbsent(key,user);
    }

    @Override
    public Boolean delUser(Integer id) {
        return null;
    }

    @Override
    public Boolean updateUser(User user) {
        return null;
    }
}
